package dao

import (
	"miao/config"
	"miao/models"
)

// GetUserRoleByUserId 获取用户角色
func GetUserRoleByUserId(userId string) ([]models.RoleBase, error) {
	var roles []models.RoleBase
	config.DB.Table("t_base_role r").Joins("LEFT JOIN t_user_role ur ON ur.role_id =  r.id").
		Where("ur.user_id = ?", userId).Find(&roles)
	return roles, nil
}

// SaveRole 保存角色
func SaveRole(role *models.RoleBase) error {
	config.DB.Create(role)
	return nil
}

// PageRole 分页查询角色
func PageRole(currentPage int, pageSize int, roleName string) ([]models.RoleBase, int64, error) {
	var roles []models.RoleBase
	var total int64
	offset := (currentPage - 1) * pageSize
	config.DB.Where("role_name LIKE ?", "%"+roleName+"%").Limit(pageSize).Offset(offset).Find(&roles).Count(&total)
	return roles, total, nil
}

// DeleteRole 删除角色
func DeleteRole(roleId string) error {
	config.DB.Where("id = ?", roleId).Delete(&models.RoleBase{})
	return nil
}

// DeleteUserRoleByRoleId 删除用户角色
func DeleteUserRoleByRoleId(userId string) error {
	config.DB.Where("user_id = ?", userId).Delete(&models.RoleBase{})
	return nil
}
